<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item :label="$t('配方名称')">
          <el-input
            v-model="listQuery.formulaName"
            clearable
            class="filter-item"
            style="width: 200px"
            @clear="handleFilter"
            :placeholder="$t('配方名称')"
          />
        </el-form-item>
        <el-form-item :label="$t('配方类型')">
          <el-select
            v-model="listQuery.formulaTypeId"
            clearable
            filterable
            class="filter-item"
            @clear="handleFilter"
            :placeholder="$t('请选择配方类型')"
          >
            <el-option
              v-for="item in formulaTypeList"
              :key="item.id"
              :value="item.id"
              :label="item.formulaTypeName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('状态')">
          <el-select
            style="width: 180px"
            v-model="listQuery.status"
            @clear="handleFilter"
            :placeholder="$t('状态')"
            clearable
          >
            <el-option :label="$t('开启')" value="1"></el-option>
            <el-option :label="$t('关闭')" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            class="filter-item"
            icon="el-icon-search"
            @click="handleFilter"
            >{{ $t("Search") }}</el-button
          >

          <el-button
            class="filter-item"
            icon="el-icon-plus"
            @click="handerCreate"
            >{{ $t("添加配方") }}</el-button
          >

          <el-button
            v-permission="['GET /admin/p/goods_goods_accessories']"
            class="filter-item"
            @click="openFormulaMaterialDrawer"
            type="warning"
            icon="el-icon-coffee"
            >{{ $t("配方原料") }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-alert
          title="模板标记说明：模板标记只为做一个记号，表示“我”标记了一个配方为模板。(辅助复制配方功能)"
          type="warning"
          show-icon>
        <span>① <i :style="{'color': '#e6a23c',fontWeight:'bolder'}" class="el-icon-copy-document"></i> 模板标记不限制任何配方，所有配方均可打上标记。</span><br>
        <span>② 标记只为做一个记号，表示“我”标记了一个配方为模板。</span><br>
        <span>③ 是为方便辅助复制配方功能，复制时可以快速知道那个是“我”配置的模板。</span><br>
        <span>④ 模板标记没有任务侵入性，被标记的模板依旧可以直接为商品配置。</span><br>
      </el-alert><br>
    </div>


    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe :row-style="{height: '80px'}"
      :element-loading-text="$t('Searching')"
      ref="table"
    >
      <el-table-column
      type="index"
      :label="$t('序号')"
      :index="countFormual"
      width="50">
    </el-table-column>

      <el-table-column
        align="center"
        min-width="100"
        :label="$t('配方名称')"
        prop="formulaName"
      >
        <template slot-scope="scope">
          {{ scope.row.formulaName }}
          <i v-if="scope.row.template" :style="{'color': '#e6a23c',fontWeight:'bolder'}" class="el-icon-copy-document">【{{ $t('模板') }}】</i>
        </template>
      </el-table-column>


      <el-table-column
        align="center"
        min-width="100"
        :label="$t('配方类型')"
        prop="formulaTypeId"
      >
        <template slot-scope="scope">
          <span :style="{ color: formateFormulaType(scope.row).typeColour }">{{
            formateFormulaType(scope.row).formulaTypeName
          }}</span> <el-tag>{{ getTypeLabel(formateFormulaType(scope.row).type)}}</el-tag>
        </template></el-table-column
      >

      <el-table-column
        align="center"
        min-width="100"
        :label="$t('状态')"
        prop="status"
      >
        <template slot-scope="scope">
          <el-link :underline="false" :type="scope.row.status == 0? 'danger':'success'">{{ scope.row.status == 0? $t("关闭"):$t("开启") }}</el-link>
        </template>
      </el-table-column>

      <el-table-column
          align="center"
          min-width="100"
          :label="$t('关联商品')"
          prop="status"
      >
        <template slot-scope="scope">
          <el-popover placement="left" trigger="click">
            <el-table :data="scope.row.goodsList">
              <el-table-column type="index" width="50" label="序号"></el-table-column>
              <el-table-column align="center" width="120" :label="$t('商品图片')" prop="status">
                <template slot-scope="scope">
                  <el-image style="width: 100px; height: 100px" :src="scope.row.picUrl" fit="contain"></el-image>
                </template>
              </el-table-column>
              <el-table-column width="100" property="name" :label="$t('商品名称')"></el-table-column>
              <el-table-column align="center" min-width="100" :label="$t('商品类型')" prop="status">
                <template slot-scope="scope">
                  {{ scope.row.type==0?$t('总部'):$t('门店') }}
                </template>
              </el-table-column>
              <el-table-column align="center" min-width="100" :label="$t('是否上架')" prop="status">
                <template slot-scope="scope">
                  <span :style="{color: scope.row.isOnSale==1?'green':'red'}">{{ scope.row.isOnSale==1?$t('上架'):$t('下架') }}</span>
                </template>
              </el-table-column>
              <el-table-column
                  align="center"
                  :label="$t('Operate')"
                  width="300"
                  fixed="right"
                  class-name="small-padding fixed-width"
              >
                <template slot="header" slot-scope="{ row }">
                  {{ $t("Operate") }}
                  <i class="el-icon-setting" style="color: #d35e32"></i>
                </template>

                <template slot-scope="subScope">
                  <el-row>
                    <el-button :disabled="subScope.row.isOnSale==1" type="danger" icon="el-icon-circle-close" size="small" @click="handleFormulaUnbundle(scope.row.id,subScope.row.id)">
                      {{ $t("解除绑定") }}
                    </el-button>
                    <el-button type="primary" icon="el-icon-edit-outline" size="small" @click="handleGoodsDetails(subScope.row)">
                      {{ $t("详情") }}
                    </el-button>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
            <el-link slot="reference" type="primary">
              {{ $t('商品数量') }} {{ scope.row.goodsList.length }}
            </el-link>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        min-width="100"
        :label="$t('更新时间')"
        prop="updateTime"
      />
      <el-table-column
        align="center"
        min-width="100"
        :label="$t('配方备注')"
        show-overflow-tooltip="true"
        prop="formulaRemark"
      />

      <el-table-column
        align="center"
        :label="$t('Operate')"
        width="300"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot="header" slot-scope="{ row }">
          {{ $t("Operate") }}
          <i class="el-icon-setting" style="color: #d35e32"></i>
        </template>

        <template slot-scope="scope">
          <el-row>
            <el-button
              type="primary"
              icon="el-icon-edit"
              plain1
              size="small"
              v-if="scope.row.status == 0"
              @click="handerEdit(scope.row)"
              >{{ $t("Edit") }}
            </el-button>

            <el-button
              type="primary"
              icon="el-icon-edit"
              plain1
              size="small"
              v-if="scope.row.status == 1"
              @click="handerDetails(scope.row)"
              >{{ $t("详情") }}
            </el-button>
            <el-button
              icon="el-icon-delete"
              plain1
              type="danger"
              size="small"
              v-if="scope.row.status == 0"
              @click="handerDelete(scope.row)"
              >{{ $t("删除") }}
            </el-button>

            <el-button
              type="warning"
              icon="el-icon-refresh"
              plain1
              size="small"
              @click="handerOpenClose(scope.row)"
              >{{ scope.row.status == 0 ? $t("开启") : $t("关闭") }}
            </el-button>


          </el-row>
          <el-row style="padding-top: 10px">
<!--            <el-button
              v-if="scope.row.status == 1"
              type="primary"
              icon="el-icon-plus"
              plain1
              size="small"
              @click="handerAddFormulaMaterial(scope.row)"
              >{{ $t("添加原料") }}
            </el-button>-->
            <el-button
                v-if="scope.row.status == 1"
                type="primary"
                icon="el-icon-plus"
                plain1
                size="small"
                @click="handeleAddSpecifications(scope.row)"
            >{{ $t("查看规格") }}
            </el-button>

            <el-popconfirm
                title="确定复制一份该配方吗？"
                @confirm="handeleCopySpecifications(scope.row)"
            >
              <el-button
                  slot="reference"
                  type="success"
                  icon="el-icon-copy-document"
                  plain1
                  size="small"
              >{{ $t("复制配方") }}
              </el-button>
            </el-popconfirm>


          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 第一个弹框-添加配方 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('配方设置')"
        :visible.sync="dialogVisible1"
        width="40%"
        :before-close="handleClose"
        :close-on-click-modal="false"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="formulaForm"
            :rules="rules"
            ref="formulaForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item :label="$t('配方名称')" prop="formulaName">
              <el-input
                v-model="formulaForm.formulaName"
                :placeholder="$t('请输入配方名称')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('排序')" prop="sort">
              <el-input
                  v-model="formulaForm.sort"
                  :placeholder="$t('排序号')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('配方类型')" prop="formulaTypeId">
              <el-select
                v-model="formulaForm.formulaTypeId"
                clearable
                class="filter-item"
                :placeholder="$t('请选择配方类型')"
              >
                <el-option
                  v-for="item in formulaTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.formulaTypeName"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('配方备注')">
              <el-input
                v-model="formulaForm.formulaRemark"
                :placeholder="$t('请输入配方备注')"
                type="textarea"
                :autosize="{ minRows: 3 }"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('配方模板')">
              <el-switch
                  v-model="formulaForm.template"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-text="$t('是')"
                  :inactive-text="$t('否')"
              >
              </el-switch>
            </el-form-item>

            <el-form-item>
              <el-button
                icon="el-icon-check"
                type="primary"
                @click="submitForm('formulaForm')"
                >{{ $t("立即创建") }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 第二个弹框-编辑配方 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('编辑')"
        :visible.sync="dialogVisible2"
        width="40%"
        :before-close="handleClose"
        :close-on-click-modal="false"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="formulaForm"
            :rules="rules"
            ref="formulaForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item :label="$t('配方名称')" prop="formulaName">
              <el-input
                v-model="formulaForm.formulaName"
                :placeholder="$t('请输入配方名称')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('排序')" prop="sort">
              <el-input
                v-model="formulaForm.sort"
                :placeholder="$t('排序号')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('配方类型')" prop="formulaTypeId">
              <el-select
                v-model="formulaForm.formulaTypeId"
                clearable
                class="filter-item"
                :placeholder="$t('请选择配方类型')"
              >
                <el-option
                  v-for="item in formulaTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.formulaTypeName"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('配方模板')">
              <el-switch
                  v-model="formulaForm.template"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-text="$t('是')"
                  :inactive-text="$t('否')"
              >
              </el-switch>
            </el-form-item>

            <el-form-item :label="$t('配方备注')" prop="formulaRemark">
              <el-input
                v-model="formulaForm.formulaRemark"
                :placeholder="$t('请输入配方备注')"
                type="textarea"
                :autosize="{ minRows: 3 }"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                v-if="dialogStatus == 'update'"
                type="primary"
                plain1
                icon="el-icon-edit"
                @click="editCardClassification('formulaForm')"
                >{{ $t("提交编辑") }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 第三个弹框-添加原料 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('添加原料')"
        :visible.sync="dialogVisible3"
        width="40%"
        :before-close="handleFormulaMaterialClose"
        :close-on-click-modal="false"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="formulaMaterialForm"
            :rules="formulaMaterialRules"
            ref="formulaMaterialForm"
            label-width="120px"
            class="demo-ruleForm"
          >

            <el-form-item :label="$t('原料分类')" >
              <el-select
                clearable
                v-model="formulaMaterialForm.materialClassificationName"
                filterable
                @change="handleMaterialListGroupByChange"
                :placeholder="$t('请选择原料分类')"
              >
                <el-option
                  v-for="item in materialClassificationListGroupBy"
                  :key="item.id"
                  :value="item.classification"
                  :label="item.classification"
                >
                  <span style="float: left">{{ item.classification }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('原料名称')" prop="materialName">
              <el-select
                  v-model="formulaMaterialForm.materialName"
                  filterable
                  @change="handleAccessoryMerChange"
                  :placeholder="$t('请选择原料名称')"
              >
                <el-option
                    v-for="item in merchandiseGroupBy"
                    :key="item.id"
                    :value="item.name"
                    :label="item.name"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>

<!--            <el-form-item
              :label="$t('原料分类')"
              prop="materialClassificationId"
            >
              <el-cascader
                v-model="formulaMaterialForm.materialClassificationId"
                :options="materialList"
                :props="{
                  label: 'classificationName',
                  value: 'id',
                }"
                :show-all-levels="false"
                clearable
                @change="handleCascaderChangeMaterialId"
              ></el-cascader>
            </el-form-item>-->

<!--            <el-form-item :label="$t('原料分类')">
              {{formulaMaterialForm.materialClassificationName}}
            </el-form-item>-->

             <el-form-item :label="$t('基本单位')">
               {{formulaMaterialForm.unit}}
            </el-form-item>

            <el-form-item :label="$t('原料图片')" prop="materialImg">
              <el-upload
                :headers="headers"
                :action="uploadPath"
                :show-file-list="false"
                :on-success="uploadPicUrl"
                class="avatar-uploader"
                accept=".jpg,.jpeg,.png,.gif"
              >
                <img
                  v-if="formulaMaterialForm.materialImg"
                  :src="formulaMaterialForm.materialImg"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <label
                  v-if="formulaMaterialForm.materialImg"
                  class="el-upload-list__item-status-label avatar-uploader__status_label"
                  @click.stop="handleRemove()"
                  ><i class="el-icon-delete"></i
                ></label>
              </el-upload>
            </el-form-item>


            <el-form-item :label="$t('单位')" style="display: none">
              {{ accessoryForm.basicUnit }}
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                plain1
                icon="el-icon-check"
                @click="addFormulaMaterialOperation('formulaMaterialForm')"
                >{{ $t("立即创建") }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 第四个弹框-编辑原料 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('编辑原料')"
        :visible.sync="dialogVisible4"
        width="40%"
        :before-close="handleFormulaMaterialClose"
        :close-on-click-modal="false"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="formulaMaterialForm"
            :rules="formulaMaterialRulesEdit"
            ref="formulaMaterialForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item :label="$t('原料分类')" >
              <span
                  :style="{
                color: formulaMaterialForm.classificationColour
              }"
              >{{
                  formulaMaterialForm.classificationName
                }}</span
              >
            </el-form-item>

             <el-form-item :label="$t('原料名称')" >
              {{formulaMaterialForm.materialName}}
            </el-form-item>

<!--            <el-form-item
              :label="$t('原料分类')"
              prop="materialClassificationId"
            >
              <el-cascader
                v-model="formulaMaterialForm.materialClassificationId"
                :options="materialList"
                :props="{
                  label: 'classificationName',
                  value: 'id',
                  emitPath: false,
                }"
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>-->

<!--            <el-form-item :label="$t('原料类型')" prop="materialType">
              <el-select
                v-model="formulaMaterialForm.materialType"
                clearable
                class="filter-item"
                :placeholder="$t('请选择原料类型')"
              >
                <el-option
                  v-for="item in materialTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.type"
                ></el-option>
              </el-select>
            </el-form-item>-->



<!--            <el-form-item :label="$t('原料名称')" prop="materialName">
              <el-select
                v-model="formulaMaterialForm.materialName"
                filterable
                @change="handleAccessoryMerChange"
                :placeholder="$t('请选择原料名称')"
              >
                <el-option
                  v-for="item in merchandise"
                  :value="item.name"
                  :label="item.name"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span
                    v-if="item.isRrc"
                    style="float: right; color: #8492a6; font-size: 13px"
                    ><i class="el-icon-coffee"></i>{{ $t("原料") }}</span
                  >
                </el-option>
              </el-select>
            </el-form-item>-->

            <el-form-item :label="$t('基本单位')">
              {{formulaMaterialForm.unit}}
            </el-form-item>

            <!-- <el-form-item :label="$t('原料名称')" prop="materialName">
              <el-cascader
                v-model="formulaMaterialForm.materialName"
                :options="materialList"
                :props="{
                  label: 'classificationName',
                  value: 'classificationName',
                }"
                :show-all-levels="false"
                change-on-select
                clearable
                @change="handleCascaderChange"
              ></el-cascader>
            </el-form-item> -->

            <!-- <el-form-item :label="$t('原料图片')">
              <el-input
                v-model="formulaMaterialForm.materialImg"
                :placeholder="$t('请输入原料图片')"
                disabled
              ></el-input>
            </el-form-item> -->

            <el-form-item :label="$t('原料图片')" prop="materialImg">
              <el-upload
                :limit="5"
                :headers="headers"
                :show-file-list="false"
                :action="uploadPath"
                :on-success="uploadPicUrl"
                class="avatar-uploader"
                accept=".jpg,.jpeg,.png,.gif"
              >
                <img
                  v-if="formulaMaterialForm.materialImg"
                  :src="formulaMaterialForm.materialImg"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <label
                  v-if="formulaMaterialForm.materialImg"
                  class="el-upload-list__item-status-label avatar-uploader__status_label"
                  @click.stop="handleRemove()"
                  ><i class="el-icon-delete"></i
                ></label>
              </el-upload>
            </el-form-item>

<!--            <el-form-item :label="$t('是否可替换')">
              <el-switch
                v-model="formulaMaterialForm.isReplaceMaterial"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-text="$t('是')"
                :inactive-text="$t('否')"
              >
              </el-switch>
            </el-form-item>

            <el-form-item :label="$t('是否显示')">
              <el-switch
                v-model="formulaMaterialForm.isDisplay"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-text="$t('是')"
                :inactive-text="$t('否')"
              >
              </el-switch>
            </el-form-item>-->

            <el-form-item :label="$t('单位')" style="display: none">
              {{ accessoryForm.basicUnit }}
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                plain1
                icon="el-icon-check"
                @click="updateFormulaMaterialOperation('formulaMaterialForm')"
                >{{ $t("提交编辑") }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 第五个弹框-配方详情 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('编辑')"
        :visible.sync="dialogVisible5"
        width="40%"
        :before-close="handleClose"
        :close-on-click-modal="false"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="formulaForm"
            :rules="rules"
            ref="formulaForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item :label="$t('配方名称')" prop="formulaName">
              <el-input
                disabled
                v-model="formulaForm.formulaName"
                :placeholder="$t('请输入配方名称')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('配方类型')" prop="formulaTypeId">
              <el-select
                disabled
                v-model="formulaForm.formulaTypeId"
                clearable
                class="filter-item"
                :placeholder="$t('请选择配方类型')"
              >
                <el-option
                  v-for="item in formulaTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.formulaTypeName"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('配方备注')" prop="formulaRemark">
              <el-input
                disabled
                v-model="formulaForm.formulaRemark"
                :placeholder="$t('请输入配方备注')"
                type="textarea"
                :autosize="{ minRows: 3 }"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 配方原料列表 -->
    <el-drawer
      :visible.sync="drawer"
      direction="ltr"
      size="90%"
      :before-close="handleClose"
    >
      <div class="filter-container" style="width: 67%; margin: auto">
        <el-row>
          <el-select
            clearable
            @change="openFormulaMaterialDrawer"
            v-model="formualMaterialQuery.materialClassificationName"
            filterable
            :placeholder="$t('请选择原料分类')"
          >
            <el-option
              v-for="item in materialClassificationListGroupBy"
              :key="item.id"
              :value="item.classification"
              :label="item.classification"
            >
              <span style="float: left">{{ item.classification }}</span>
            </el-option>
          </el-select>
          <el-input
            clearable
            size="small"
            style="width: 180px"
            @change="openFormulaMaterialDrawer"
            :placeholder="$t('请输入原料名称')"
            suffix-icon="el-icon-coffee"
            v-model="formualMaterialQuery.materialName"
          ></el-input>
          <el-button
            type="info"
            size="small"
            @click="openFormulaMaterialDrawer"
            plain1
            icon="el-icon-search"
          ></el-button>
          <el-button
              size="small"
              @click="openFormulaMaterialDrawer"
              plain1
              icon="el-icon-refresh"
          >{{ $t("刷新列表") }}</el-button>
<!--          <el-button
              type="primary"
              icon="el-icon-plus"
              plain1
              size="small"
              @click="handerAddFormulaMaterial"
          >{{ $t("添加原料") }}
          </el-button>-->
        </el-row>
      </div>

      <el-table
        v-loading="formulaMaterialDrawer"
        :element-loading-text="$t('拼命加载中')"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.5)"
        ref="handSelectTest_multipleTable"
        :data="formualMaterialList.list"
        stripe
        border
        style="width: 95%; margin: auto"
      >

        <el-table-column
          type="index"
          :label="$t('序号')"
          :index="countMaterial"
          width="50">
        </el-table-column>
        <el-table-column
          align="center"
          prop="materialName"
          :label="$t('原料名称')"
          width="180"
        ></el-table-column>

<!--        <el-table-column-->
<!--          align="center"-->
<!--          min-width="100"-->
<!--          :label="$t('原料编号')"-->
<!--          prop="materialType"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ scope.row.merchandiseSn }}</span>-->
<!--          </template></el-table-column-->
<!--        >-->

        <el-table-column
          align="center"
          min-width="100"
          :label="$t('规格')"
          prop="materialType"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.standard }}</span>
          </template></el-table-column
        >
        <el-table-column
            align="center"
            min-width="100"
            :label="$t('属性')"
            prop="materialType"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.property }}</span>
          </template></el-table-column
        >

        <el-table-column
          align="center"
          :label="$t('原料图片')"
          prop="materialImg"
        >
          <template slot-scope="scope">
            <el-image
              preview-src-list
              style="border-radius: 7%; width: 80px"
              :src="scope.row.materialImg"
              width="20"
              lazy
            >
              <div slot="error" class="image-slot">
                <i style="font-size: 30px" class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>



<!--        <el-table-column
          align="center"
          min-width="100"
          :label="$t('原料分类')"
          prop="materialClassificationId"
        >
          <template slot-scope="scope">
            <span
              :style="{
                color: getClassificationName(scope.row.materialClassificationId)
                  .classificationColour,
              }"
              >{{
                getClassificationName(scope.row.materialClassificationId)
                  .classificationName
              }}</span
            >
          </template></el-table-column
        >-->
                <el-table-column
          align="center"
          min-width="100"
          :label="$t('原料分类')"
          prop="materialClassificationId"
        >
          <template slot-scope="scope">
            <span
              :style="{
                color: scope.row.classificationColour
              }"
              >{{
                scope.row.materialClassificationName
              }}</span
            >
          </template></el-table-column
        >
<!--        <el-table-column
          align="center"
          min-width="100"
          :label="$t('原料分类')"
          prop="materialType"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.materialClassificationName }}</span>
          </template></el-table-column
        >-->


        <el-table-column
            align="center"
            min-width="100"
            :label="$t('基本单位')"
            prop="materialType"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.basicUnit }}</span>
          </template></el-table-column
        >

<!--
<el-table-column
            align="center"
            min-width="100"
            :label="$t('原料单位')"
            prop="materialType"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.unit }}</span>
          </template></el-table-column
        >
        <el-table-column
          align="center"
          min-width="100"
          :label="$t('盘点单位')"
          prop="materialType"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.checkUnit }}</span>
          </template></el-table-column
        >

        <el-table-column
          align="center"
          min-width="100"
          :label="$t('盘点比例')"
          prop="materialType"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.checkRatio }}</span>
          </template></el-table-column
        >-->



        <!--  <el-table-column
           align="center"
           min-width="100"
           :label="$t('原料数量')"
           prop="materialType"
         >
           <template slot-scope="scope">
             <span>{{ scope.row.number }}</span>
           </template></el-table-column
         >

        <el-table-column
           align="center"
           min-width="100"
           :label="$t('进货价格')"
           prop="materialType"
         >
           <template slot-scope="scope">
             <span>${{ scope.row.purchasePrice }}</span>
           </template></el-table-column
         >

         <el-table-column
           align="center"
           min-width="100"
           :label="$t('销售价格')"
           prop="materialType"
         >
           <template slot-scope="scope">
             <span>${{ scope.row.sellingPrice }}</span>
           </template></el-table-column
         >-->

<!--        <el-table-column-->
<!--          align="center"-->
<!--          min-width="100"-->
<!--          :label="$t('标签')"-->
<!--          prop="materialType"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ scope.row.label }}</span>-->
<!--          </template></el-table-column-->
<!--        >-->


<!--        <el-table-column-->
<!--          align="center"-->
<!--          min-width="100"-->
<!--          :label="$t('品牌')"-->
<!--          prop="materialType"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ scope.row.brand }}</span>-->
<!--          </template></el-table-column-->
<!--        >-->

        <el-table-column
          align="center"
          :label="$t('Operate')"
          width="350"
          class-name="small-padding fixed-width"
        >
          <template slot="header" slot-scope="{ row }">
            {{ $t("Operate") }}
            <i class="el-icon-setting" style="color: #d35e32"></i>
          </template>

          <template slot-scope="scope">
            <el-row>
              <el-button
                icon="el-icon-edit"
                plain
                size="small"
                @click="handerFormulaMaterialEdit(scope.row)"
              >{{ $t("编辑原料") }}
              </el-button>

              <el-button
                type="primary"
                icon="el-icon-edit"
                plain1
                size="small"
                @click="handerFormulaMaterialUnitEdit(scope.row)"
                >{{ $t("编辑单位") }}
              </el-button>

              <el-button
                  icon="el-icon-delete"
                  plain1
                  type="danger"
                  size="small"
                  @click="deleteFormulaMaterialOperation(scope.row)"
              >{{ $t("删除") }}
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="formualMaterialList.total > 0"
        :total="formualMaterialList.total"
        :page.sync="formualMaterialQuery.page"
        :limit.sync="formualMaterialQuery.limit"
        @pagination="openFormulaMaterialDrawer"
      />
    </el-drawer>

    <!-- 第六个弹框-编辑配方原料单位 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('编辑单位')"
        :visible.sync="dialogVisible6"
        width="40%"
        :before-close="handleClose"
        :close-on-click-modal="false"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="formulaMaterialForm"
            :rules="formulaMaterialRulesUnitEdit"
            ref="formulaMaterialForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item :label="$t('单位')"  prop="unit">
              <el-input
                v-model="formulaMaterialForm.unit"
                :placeholder="$t('请输入规格单位')"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                plain1
                icon="el-icon-check"
                @click="updateFormulaMaterialUnitOperation('formulaMaterialForm')"
                >{{ $t("提交编辑") }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>
  </div>
</template>


<script>
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
// import { list, add, update, deleteById } from "@/api/materialClassification";
import { listFormula, add, update, deleteById,copyFormula ,unbundleGoodsFormulaCorrelation} from "@/api/formula";
import { listType } from "@/api/formulaType";
import { list ,listGroupBy} from "@/api/materialClassification";
import {
  listFormulaMaterial,
  addFormulaMaterial,
  updateFormulaMaterial,
  deleteFormulaMaterial,
} from "@/api/formulaMaterial";
import { getToken } from "@/utils/auth";
import { uploadPath } from "@/api/storage";
//原料名称
import { allMerchandise } from "@/api/merchandise";
export default {
  name: "repositoryList",
  components: { Pagination },
  computed: {
    headers() {
      return {
        "X-Litemall-Admin-Token": getToken(),
      };
    },
    // 定义映射对象模拟枚举的对应关系
    typeMap() {
      return {
        1: '原料',
        2: '物品'
      };
    },
    // 计算属性根据type值获取对应的显示标签
    getTypeLabel() {
      return (type) => {
        return this.typeMap[type] || '未知类型'; // 如果不存在对应映射则显示未知类型
      };
    }
  },
  data() {
    return {
      //expandedRowKeys: [], // 控制展开的行
      formualMaterialQuery: {
        materialName: undefined,
        materialClassificationName: undefined,
        page: 1,
        limit: 10,
        total: 1,
      },
      //配方原料列表
      formualMaterialList: {
        total: 1,
        page: 1,
        limit: 10,
        materialName: undefined,
        list: [],
      },
      //打开配方原料加载
      formulaMaterialDrawer: false,
      //打开配方原料
      drawer: false,
      selectedPath: [], // 用于绑定整个路径
      uploadPath,
      list: [],
      formulaMaterialList: [],
      materialList: [],

      //原料所有分类
      materialClassificationListGroupBy:[],

      formulaTypeList: [],
      //原料名称
      merchandise: [],
      merchandiseGroupBy: [],
      //原料名称
      accessoryForm: {},

      total: 0,
      listLoading: false,
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      dialogVisible4: false,
      dialogVisible5: false,
      dialogVisible6: false,
      dialogStatus: "",
      color: "#409EFF",
      listQuery: {
        page: 1,
        limit: 20,
        classificationName: undefined,
        formulaTypeId: undefined,
        status: undefined,
      },
      formulaForm: {
        id: undefined,
        formulaName: undefined,
        formulaTypeId: undefined,
        formulaRemark: undefined,
        status: undefined,
        sort: undefined,
        template: false,
      },
      formulaMaterialForm: {
        id: undefined,
        formulaId: undefined,
        materialId: undefined,
        materialName: undefined,
        materialImg: undefined,
        materialClassificationId: undefined,
        materialClassificationName:undefined,
        isReplaceMaterial: undefined,
        isDisplay: undefined,
        unit: undefined,
      },
      formulaMaterialRulesUnitEdit:{
        unit: [
          {
            required: true,
            message: "请输入单位",
            trigger: "blur",
          },
        ],
      },
      rules: {
        formulaName: [
          {
            required: true,
            message: "请输入配方名称",
            trigger: "blur",
          },
        ],
        formulaTypeId: [
          {
            required: true,
            message: "请选择配方类型",
            trigger: "change", // 选择器使用 'change' 事件触发验证
          },
          {
            validator: (rule, value, callback) => {
              if (value === "" || value === null || value === undefined) {
                callback(new Error("请选择配方类型"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      //原料编辑校验
      formulaMaterialRulesEdit: {
        materialType: [
          {
            required: true,
            message: "请选择原料类型",
            trigger: "change", // 选择器使用 'change' 事件触发验证
          },
          {
            validator: (rule, value, callback) => {
              if (value === "" || value === null || value === undefined) {
                callback(new Error("请选择原料类型"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],

        materialName: [
          {
            required: true,
            message: "请选择原料名称",
            trigger: "change", // 选择器使用 'change' 事件触发验证
          },
          {
            validator: (rule, value, callback) => {
              if (value === "" || value === null || value === undefined) {
                callback(new Error("请选择原料名称"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      //原料添加校验
      formulaMaterialRules: {
        materialClassificationId: [
          {
            required: true,
            message: "请选择原料分类",
            trigger: "change", // 选择器使用 'change' 事件触发验证
          },
          {
            validator: (rule, value, callback) => {
              if (value === "" || value === null || value === undefined) {
                callback(new Error("请选择原料分类"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        materialType: [
          {
            required: true,
            message: "请选择原料类型",
            trigger: "change", // 选择器使用 'change' 事件触发验证
          },
          {
            validator: (rule, value, callback) => {
              if (value === "" || value === null || value === undefined) {
                callback(new Error("请选择原料类型"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],

        materialName: [
          {
            required: true,
            message: "请选择原料名称",
            trigger: "change", // 选择器使用 'change' 事件触发验证
          },
          {
            validator: (rule, value, callback) => {
              if (value === "" || value === null || value === undefined) {
                callback(new Error("请选择原料名称"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    // 获取并填充主列表
    this.getList();
    // 获取并填充配方类型列表
    this.getFormulaTypeList();
    // 获取并填充原料分类列表
    this.getMaterialClassificationList();
    // 获取原料名称列表
    this.handleAccessoryShow();
    this.getListGroupBy();
  },
  methods: {
    handleMaterialListGroupByChange(selectedClassification) {
      // 使用三元运算符，简化赋值逻辑
      this.merchandiseGroupBy = selectedClassification
        ? this.merchandise.filter(item => item.classification === selectedClassification)
        : this.merchandise;
    },

    handleAccessoryMerChange() {
      let m = this.merchandise.find((item) => {
        if (item.name == this.formulaMaterialForm.materialName) {
          return item;
        }
      });
      console.log(77);
      console.log(this.merchandise);
      this.accessoryForm.groupName = m.name;
      this.accessoryForm.name = m.name;
      this.accessoryForm.model = m.model;
      this.accessoryForm.unit = m.unit;
      this.accessoryForm.basicUnit = m.basicUnit;

      this.formulaMaterialForm.unit = m.basicUnit;
      this.formulaMaterialForm.materialId = m.id;

      this.formulaMaterialForm.materialClassificationName = m.classification;
    },
    handleAccessoryShow() {
      this.loadAllMerchandise();
      this.accessoryForm = {
        accessoryGroupName: "",
        groupName: "",
        name: "",
        price: 0.0,
        consumeRatio: 1,
      };
    },
    loadAllMerchandise() {
      allMerchandise({ goodsId: this.$route.query.id }).then((response) => {
        this.merchandise = response.data.data;
      });
    },
    uploadPicUrl: function (response) {
      this.formulaMaterialForm.materialImg = response.data.url;
    },
    getListGroupBy(){
      listGroupBy()
        .then((response) => {
          this.materialClassificationListGroupBy = response.data.data;
        })
        .catch(() => {
          this.materialClassificationListGroupBy = [];
        });
    },
    getList() {
      this.listLoading = true;
      listFormula(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    getIndex(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.limit;
    },
    handleFilter() {
      this.getList();
    },
    handerCreate() {
      this.dialogVisible1 = true;
      this.dialogStatus = "create";
      this.formulaForm = {
        id: undefined,
        formulaName: undefined,
        formulaTypeId: undefined,
        formulaRemark: undefined,
      };
    },
    handerCreateSubclass(row) {
      this.dialogVisible1 = true;
      this.dialogStatus = "create";
      this.formulaForm.pid = row;
    },
    handleClose(done) {
      //this.getList();
      done();
    },
    handleFormulaMaterialClose(done) {
      done();
    },
    handerEdit(row) {
      this.dialogVisible2 = true;
      this.dialogStatus = "update";
      //   this.formulaForm = row;
      this.formulaForm.id = row.id;
      this.formulaForm.formulaName = row.formulaName;
      this.formulaForm.formulaTypeId = row.formulaTypeId;
      this.formulaForm.formulaRemark = row.formulaRemark;
      this.formulaForm.template = row.template;
    },

    handerDetails(row) {
      this.dialogVisible5 = true;
      this.dialogStatus = "details";
      //   this.formulaForm = row;
      this.formulaForm.id = row.id;
      this.formulaForm.formulaName = row.formulaName;
      this.formulaForm.formulaTypeId = row.formulaTypeId;
      this.formulaForm.formulaRemark = row.formulaRemark;
    },

    handleGoodsDetails(row) {
      this.$router.push({ path: '/goods/edit', query: { id: row.id }})
    },
    //解除配方绑定
    handleFormulaUnbundle(id,subId){
      var goodsFormulaCorrelation = {
        goodsId: subId,
        formulaId: id,
      };
      unbundleGoodsFormulaCorrelation(goodsFormulaCorrelation)
          .then((res) => {
            this.$notify({
              title: "成功",
              message: "解除成功",
              type: "success",
            });
            this.LoadGoodsFormulaSpecifications();
            this.init();
            this.whetherCustomization();
            this.showGoodsFormulaTable = false;
            this.goodsFormulaName = undefined;
          })
          .catch((error) => {

          });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          add(this.formulaForm)
            .then((res) => {
              if (res.data.data == 100) {
                this.$notify({
                  title: "警告",
                  message: "这是一条警告的提示消息",
                  type: "warning",
                });
              } else {
                this.dialogVisible1 = false;
                this.$notify({
                  title: "成功",
                  message: "添加成功",
                  type: "success",
                });
                this.listQuery.formulaName = this.formulaForm.formulaName
                this.getList();
                this.$refs["formulaForm"].resetFields();
              }
            })
            .catch((error) => {
              console.error("请求错误：", error);
              if (error.data.errno == 1002) {
                this.$notify.error({
                  title: "错误",
                  message: error.data.errmsg,
                });
              } else {
                this.$notify.error({
                  title: "错误",
                  message: "创建失败",
                });
              }
              // this.$notify.error({
              //   title: "错误",
              //   message: "创建失败",
              // });
            });
        } else {
          return false;
        }
      });
    },

    editCardClassification(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          update(this.formulaForm)
            .then((res) => {
              this.dialogVisible2 = false;
              this.$notify({
                title: "成功",
                message: "编辑成功",
                type: "success",
              });
              this.$refs["formulaForm"].resetFields();
              this.getList();
            })
            .catch((error) => {
              console.error("请求错误：", error);
              if (error.data.errno == 1002) {
                this.$notify.error({
                  title: "错误",
                  message: error.data.errmsg,
                });
              } else {
                this.$notify.error({
                  title: "错误",
                  message: "编辑失败",
                });
              }
              // this.$notify.error({
              //   title: "错误",
              //   message: "编辑失败",
              // });
            });
        } else {
          return false;
        }
      });
    },

    handerDelete(row) {
      var id = row.id;
      var formulaForm = {
        id: row.id,
      };
      this.$confirm("确认删除？")
        .then((_) => {
          deleteById(formulaForm)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
              this.getList();
            })
            .catch((res) => {
              this.$notify.error({
                title: "错误",
                message: "删除失败",
              });
            });
        })
        .catch((_) => {});
    },

    handerOpenClose(row) {
      var statusOpenClose = row.status == 1 ? 0 : 1;
      var formulaForm = {
        id: row.id,
        status: statusOpenClose,
      };
      this.$confirm("确认操作吗？")
        .then((_) => {
          update(formulaForm)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
              });
              this.getList();
            })
            .catch((res) => {
              this.$notify.error({
                title: "错误",
                message: "操作失败",
              });
            });
        })
        .catch((_) => {});
    },

    getFormulaTypeList() {
      var listQuery = {
        page: 1,
        limit: 10,
        classificationName: undefined,
        formulaTypeId: undefined,
      };
      listType(listQuery)
        .then((response) => {
          this.formulaTypeList = response.data.data.list;
        })
        .catch(() => {
          this.formulaTypeList = [];
        });
    },

    getMaterialClassificationList() {
      var materialClassification = {
        page: 1,
        limit: 10,
        classificationName: undefined,
      };
      list(materialClassification)
        .then((response) => {
          this.materialList = response.data.data;
        })
        .catch(() => {
          this.materialList = [];
        });
    },

    //原料分类展示
    getClassificationName(id) {
      const classification = this.materialList.find((item) => item.id === id);

      if (classification === undefined) {
        const classificationChildren = this.materialList.find((item) =>
          item.children.find((itemChildren) => itemChildren.id === id)
        );
        const children = classificationChildren.children.find(
          (item) => item.id === id
        );
        return children ? children : "未知分类";
      } else {
        return classification ? classification : "未知分类";
      }
    },

    formateFormulaType(row) {
      for (let lengthKey in this.formulaTypeList) {
        if (this.formulaTypeList[lengthKey].id == row.formulaTypeId) {
          return this.formulaTypeList[lengthKey];
        }
      }
    },

    handerAddFormulaMaterial(row) {
      this.dialogVisible3 = true;

      this.merchandiseGroupBy =  this.merchandise

      this.formulaMaterialForm = {
        id: undefined,
        //formulaId: row.id,
        materialName: undefined,
        materialImg: undefined,
        materialType: undefined,
        materialClassificationId: undefined,
        isReplaceMaterial: undefined,
        isDisplay: undefined,
        addTime: undefined,
        updateTime: undefined,
        deleted: false,
      };

      //控制展开行展开
      const tableRef = this.$refs.table;
      if (tableRef) {
        // 获取当前行是否展开的状态
        const isExpanded = tableRef.store.states.expandRows.includes(row);
        // 切换展开/收起状态
        tableRef.toggleRowExpansion(row, true);
      } else {
        console.error('Table ref not found');
      }
    },

    /**配方原料 */
    addFormulaMaterialOperation(formName) {
      var formulaMateria = this.formulaMaterialForm
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formulaMaterialForm.unit = this.accessoryForm.basicUnit;
          addFormulaMaterial(this.formulaMaterialForm)
            .then((res) => {
              if (res.data.data == 100) {
                this.$notify({
                  title: "警告",
                  message: "这是一条警告的提示消息",
                  type: "warning",
                });
              } else {
                this.dialogVisible3 = false;
                this.$notify({
                  title: "成功",
                  message: "添加成功",
                  type: "success",
                });
                  //搜索一下
                  this.formualMaterialQuery.materialName = this.formulaMaterialForm.materialName
                  this.openFormulaMaterialDrawer()

                //添加原料不刷新页面，手动添加
                const formulaId = this.formulaMaterialForm.formulaId;
                formulaMateria.id = res.data.data;

                const index = this.list.findIndex(item => item.id === formulaId);
                if (index !== -1) {
                  this.list[index].children.splice(this.list[index].children.length,0,formulaMateria)
                  this.$set(this.list[index], 'children', this.list[index].children.map(re=> Object.assign({},re)));
                }
                this.$refs["formulaMaterialForm"].resetFields();

              }
            })
            .catch(() => {
              this.$notify.error({
                title: "错误",
                message: "创建失败",
              });
            });
        } else {
          return false;
        }
      });
    },

    //递归获取所有的原料id
    // getChildrenIds(node) {
    //   let ids = [];
    //   if (node.children && node.children.length > 0) {
    //     for (let child of node.children) {
    //       ids.push(child.id);
    //       // 如果有嵌套的children, 可以继续递归调用
    //       if (child.children && child.children.length > 0) {
    //         ids = ids.concat(this.getChildrenIds(child));
    //       }
    //     }
    //   }
    //   return ids;
    // },

    updateFormulaMaterialOperation(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formulaMaterialForm.unit = this.accessoryForm.basicUnit;
          updateFormulaMaterial(this.formulaMaterialForm)
            .then((res) => {
              this.dialogVisible4 = false;
              this.$notify({
                title: "成功",
                message: "编辑成功",
                type: "success",
              });
              //替换原料不刷新页面，手动更新
              // const index = this.list.findIndex(item => item.id === this.formulaMaterialForm.formulaId);
              // if (index !== -1) {
              //   this.list[index].children.splice(index-1,index-1,this.formulaMaterialForm)
              // }

              //配方位置
              let parentIndex = -1;
              //原料位置
              let childIndex = -1;

              parentIndex = this.list.findIndex(item => {
                  childIndex = item.children.findIndex(itemChildren => itemChildren.id === this.formulaMaterialForm.id);
                  return childIndex !== -1; // 如果找到子元素，则返回true，终止遍历
              });

              if (childIndex !== -1) {
                this.list[parentIndex].children.splice(childIndex,1,this.formulaMaterialForm)
              }

            })
            .catch(() => {
              this.$notify.error({
                title: "错误",
                message: "编辑失败",
              });
            });
        } else {
          return false;
        }
      });
    },
    deleteFormulaMaterialOperation(row) {
      var formulaMaterialForm = {
        id: row.id,
        //formulaId: row.formulaId
      };
      this.$confirm("确认删除？")
        .then((_) => {
          deleteFormulaMaterial(formulaMaterialForm)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });

              console.log(formulaMaterialForm)

              //配方位置
              let parentIndex = -1;
              //原料位置
              let childIndex = -1;

              parentIndex = this.list.findIndex(item => {
                  childIndex = item.children.findIndex(itemChildren => itemChildren.id === formulaMaterialForm.id);
                  return childIndex !== -1; // 如果找到子元素，则返回true，终止遍历
              });

              if (childIndex !== -1) {
                this.list[parentIndex].children.splice(childIndex,1)
              }
            })
            .catch((res) => {
              /*this.$notify.error({
                title: "错误",
                message: "删除失败",
              });*/
            });
        })
        .catch((_) => {});
    },
    handerFormulaMaterialEdit(row) {
      console.log(77);
      console.log(row);
      this.dialogVisible4 = true;
      this.formulaMaterialForm.id = row.id;
      //this.formulaMaterialForm.formulaId = row.formulaId;
      this.formulaMaterialForm.materialName = row.materialName;
      this.formulaMaterialForm.materialImg = row.materialImg;
      this.formulaMaterialForm.materialType = row.materialType;
      this.formulaMaterialForm.classificationName =
          row.classificationName;
      this.formulaMaterialForm.classificationColour =
          row.classificationColour;
      this.formulaMaterialForm.materialClassificationId =
        row.materialClassificationId;
      this.formulaMaterialForm.isReplaceMaterial = row.isReplaceMaterial;
      this.formulaMaterialForm.isDisplay = row.isDisplay;
      this.formulaMaterialForm.unit = row.unit;
    },

    handleCascaderChange(value) {
      console.log(12333333333333);
      console.log(value);
      // 当用户选择原料名称时，将其存储在 formulaMaterialForm.materialName 中
      this.formulaMaterialForm.materialName = value[value.length - 1]; // 获取最后一级的值
    },

    //获取原料分类层级
    handleCascaderChangeMaterialId(value) {
      // 当用户选择原料名称时，将其存储在 formulaMaterialForm.materialClassificationId 中
      this.formulaMaterialForm.materialClassificationId =
        value[value.length - 1];
    },

    handleRemove: function () {
      this.formulaMaterialForm.materialImg = '';
    },

    //添加规格
    handeleAddSpecifications(row) {
      // scope.row.status==0?'新增':scope.row.status==1?"上架":scope.row.status==2?'下架'
      this.$router.push({
        path: "/formula/formulaSpecifications",
        // query: { id: row.id, type: 1, showType: row.status == 1 ? 2 : 1 },
        query: {
          formulaMaterialList: row.children,
          formulaId: row.id,
          formulaName: row.formulaName,
          type: this.formateFormulaType(row).type,
        },
      });
    },

    //复制配方
    handeleCopySpecifications(row){
      copyFormula({id:row.id})
          .then((response) => {
            this.$message({
              message: '复制成功',
              type: 'success'
            });
            this.getList();
          })
          .catch(() => {
            this.$message.error('复制失败');
          });
    },

    //打开配方原料
    openFormulaMaterialDrawer() {
      this.formulaMaterialDrawer = true;
      this.drawer = true;
      listFormulaMaterial(this.formualMaterialQuery)
        .then((response) => {
          this.formualMaterialList.list = response.data.data.list;
          this.formualMaterialList.total = response.data.data.total;
          console.log(77);
          console.log(response.data.data);
          this.formulaMaterialDrawer = false;
        })
        .catch(() => {
          this.formualMaterialList.list = [];
          this.formualMaterialList.total = 0;
          this.formulaMaterialDrawer = false;
        });
    },

    //编辑原料单位
    handerFormulaMaterialUnitEdit(row) {
      console.log(88);
      console.log(row);
      this.dialogVisible6 = true;
      this.formulaMaterialForm.id = row.id;
      this.formulaMaterialForm.unit = row.unit;
    },

    updateFormulaMaterialUnitOperation() {
      updateFormulaMaterial(this.formulaMaterialForm)
        .then((res) => {
          this.dialogVisible6 = false;
          this.$notify({
            title: "成功",
            message: "编辑成功",
            type: "success",
          });
          this.openFormulaMaterialDrawer();
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "编辑失败",
          });
        });
    },
    countMaterial(index) {
      return (this.formualMaterialQuery.page - 1) * this.formualMaterialQuery.limit + index + 1
    },
    countFormual(index) {
      return (this.listQuery.page - 1) * this.listQuery.limit + index + 1
    }
  },
  filters: {},

};
</script>
<style scoped>
.circle {
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 50%;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.avatar-uploader__status_label {
  display: block;
  color: red;
  cursor: pointer;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>
